"""
提示词管理API端点
"""

from typing import List
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session

from app.database import get_db
from app.services.prompt_service import PromptService
from app.schemas.prompt_template import (
    PromptTemplateCreate, PromptTemplateUpdate, PromptTemplateResponse,
    PromptTemplateRenderRequest, PromptTemplateRenderResponse,
    PromptTemplateSearchRequest
)

router = APIRouter()
prompt_service = PromptService()


@router.get("", response_model=List[PromptTemplateResponse])
async def get_prompts(
    skip: int = 0,
    limit: int = 100,
    category: str = None,
    is_public: bool = None,
    db: Session = Depends(get_db)
):
    """获取提示词模板列表"""
    try:
        filters = {}
        if is_public is not None:
            filters["is_public"] = is_public
        if category:
            filters["category"] = category
        
        prompts = prompt_service.get_multi(
            db=db,
            skip=skip,
            limit=limit,
            filters=filters
        )
        
        return prompts
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取提示词列表失败: {str(e)}")


@router.get("/active", response_model=List[PromptTemplateResponse])
async def get_active_prompts(
    db: Session = Depends(get_db)
):
    """获取激活的提示词模板"""
    try:
        prompts = prompt_service.get_active_templates(db=db)
        return prompts
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取激活提示词失败: {str(e)}")


@router.get("/public", response_model=List[PromptTemplateResponse])
async def get_public_prompts(
    db: Session = Depends(get_db)
):
    """获取公开的提示词模板"""
    try:
        prompts = prompt_service.get_public_templates(db=db)
        return prompts
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取公开提示词失败: {str(e)}")


@router.get("/popular", response_model=List[PromptTemplateResponse])
async def get_popular_prompts(
    limit: int = Query(default=10, le=50),
    db: Session = Depends(get_db)
):
    """获取热门提示词模板"""
    try:
        prompts = prompt_service.get_popular_templates(db=db, limit=limit)
        return prompts
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取热门提示词失败: {str(e)}")


@router.get("/{prompt_id}", response_model=PromptTemplateResponse)
async def get_prompt(
    prompt_id: int,
    db: Session = Depends(get_db)
):
    """获取提示词模板详情"""
    try:
        prompt = prompt_service.get(db=db, id=prompt_id)
        if not prompt:
            raise HTTPException(status_code=404, detail="提示词模板不存在")
        
        return prompt
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取提示词详情失败: {str(e)}")


@router.post("", response_model=PromptTemplateResponse)
async def create_prompt(
    prompt: PromptTemplateCreate,
    db: Session = Depends(get_db)
):
    """创建提示词模板"""
    try:
        new_prompt = prompt_service.create_template(
            db=db,
            name=prompt.name,
            content=prompt.content,
            description=prompt.description,
            category=prompt.category,
            tags=prompt.tags,
            is_public=prompt.is_public
        )
        
        return new_prompt
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建提示词失败: {str(e)}")


@router.put("/{prompt_id}", response_model=PromptTemplateResponse)
async def update_prompt(
    prompt_id: int,
    prompt_update: PromptTemplateUpdate,
    db: Session = Depends(get_db)
):
    """更新提示词模板"""
    try:
        existing_prompt = prompt_service.get(db=db, id=prompt_id)
        if not existing_prompt:
            raise HTTPException(status_code=404, detail="提示词模板不存在")
        
        updated_prompt = prompt_service.update(
            db=db,
            db_obj=existing_prompt,
            obj_in=prompt_update
        )
        
        return updated_prompt
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新提示词失败: {str(e)}")


@router.delete("/{prompt_id}")
async def delete_prompt(
    prompt_id: int,
    db: Session = Depends(get_db)
):
    """删除提示词模板"""
    try:
        success = prompt_service.delete(db=db, id=prompt_id)
        if not success:
            raise HTTPException(status_code=404, detail="提示词模板不存在")
        
        return {"message": "提示词模板删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除提示词失败: {str(e)}")


@router.post("/search", response_model=List[PromptTemplateResponse])
async def search_prompts(
    request: PromptTemplateSearchRequest,
    db: Session = Depends(get_db)
):
    """搜索提示词模板"""
    try:
        prompts = prompt_service.search_templates(
            db=db,
            query=request.query,
            category=request.category
        )
        
        return prompts
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"搜索提示词失败: {str(e)}")


@router.get("/category/{category}", response_model=List[PromptTemplateResponse])
async def get_prompts_by_category(
    category: str,
    db: Session = Depends(get_db)
):
    """根据分类获取提示词模板"""
    try:
        prompts = prompt_service.get_templates_by_category(db=db, category=category)
        return prompts
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取分类提示词失败: {str(e)}")


@router.post("/{prompt_id}/render", response_model=PromptTemplateRenderResponse)
async def render_prompt(
    prompt_id: int,
    request: PromptTemplateRenderRequest,
    db: Session = Depends(get_db)
):
    """渲染提示词模板"""
    try:
        prompt = prompt_service.get(db=db, id=prompt_id)
        if not prompt:
            raise HTTPException(status_code=404, detail="提示词模板不存在")
        
        # 渲染模板
        rendered_content = prompt_service.render_template(
            template_content=prompt.content,
            variables=request.variables
        )
        
        # 检查缺失的变量
        template_variables = prompt_service.get_template_variables(prompt.content)
        variables_used = list(request.variables.keys())
        variables_missing = [var for var in template_variables if var not in variables_used]
        
        return PromptTemplateRenderResponse(
            rendered_content=rendered_content,
            variables_used=variables_used,
            variables_missing=variables_missing
        )
        
    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"渲染提示词失败: {str(e)}")


@router.get("/{prompt_id}/variables")
async def get_prompt_variables(
    prompt_id: int,
    db: Session = Depends(get_db)
):
    """获取提示词模板变量"""
    try:
        prompt = prompt_service.get(db=db, id=prompt_id)
        if not prompt:
            raise HTTPException(status_code=404, detail="提示词模板不存在")
        
        variables = prompt_service.get_template_variables(prompt.content)
        
        return {
            "prompt_id": prompt_id,
            "variables": variables
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取提示词变量失败: {str(e)}")


@router.get("/{prompt_id}/info")
async def get_prompt_info(
    prompt_id: int,
    db: Session = Depends(get_db)
):
    """获取提示词模板信息"""
    try:
        prompt = prompt_service.get(db=db, id=prompt_id)
        if not prompt:
            raise HTTPException(status_code=404, detail="提示词模板不存在")
        
        info = prompt_service.get_template_info(prompt)
        return info
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取提示词信息失败: {str(e)}")
